import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {ActionSheetController, IonicPage, NavController, ToastController} from 'ionic-angular';
import {Storage} from '@ionic/storage';
import {User} from '../../providers/providers';
import {MainPage} from '../pages';
import {Settings} from "../../providers/settings/settings";

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  // The account fields for the login form.
  // If you're using the username field with or without userName, make
  // sure to add it to the type
  account: { accountName: string, password: string, rememberMe: boolean } = {
    accountName: '',
    password: '',
    rememberMe: true
  };

  // Our translated text strings
  private loginErrorString: string;
  private networkErrorString: string;

  constructor(public navCtrl: NavController,
              public user: User,
              public settings: Settings,
              public storage: Storage,
              public toastCtrl: ToastController,
              public actionSheetCtrl: ActionSheetController,
              public translateService: TranslateService) {

    this.translateService.get('LOGIN_ERROR').subscribe((value) => {
      this.loginErrorString = value;
    });
    this.translateService.get('NETWORK_ERROR').subscribe((value) => {
      this.networkErrorString = value;
    });
  }

  // Attempt to login in through our User service
  doLogin() {
    this.user.login(this.account).subscribe(() => {
      this.navCtrl.push(MainPage);
    }, (err) => {
      let msg = err.status == 500 ? this.loginErrorString : this.networkErrorString;
      // Unable to log in
      let toast = this.toastCtrl.create({
        message: msg,
        duration: 1000,
        position: 'top'
      });
      toast.present();
    });
  }

  signup() {
    this.navCtrl.push('SignupPage');
    return
  }

  actionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
      buttons: [
        {
          text: '找回密码',
          handler: () => {
            console.log('Destructive clicked');
            this.navCtrl.push('ForgetPwdPage');
          }
        }, {
          text: '短信验证登录',
          handler: () => {
            console.log('Archive clicked');
            this.navCtrl.push('SmsLoginPage');
          }
        }, {
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

  loginFree() {
    this.navCtrl.push("FreePage");
  }

}
